﻿using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using Newtonsoft.Json;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using static CoreShop.Library.GlobalEnumVars;

namespace CoreShop.Services.Services.System
{
    public class OrderBusiness
    {

        /// <summary>
        /// 创建充值主要订单-本地
        /// </summary>
        public PosOrderHeadDto CreateTopUpHeadOder(string tableid, decimal amountOrder, decimal amountDiscount, decimal amountFact, string BillNo, corecmsstore store, corecmsuser member, sysuser user, corecmsfoodorderclass orderClass, int orderBillTypeId = 5, string sourceNo = "")
        {
            //主要信息
            PosOrderHeadDto posOrderHeadDto = new PosOrderHeadDto();

            posOrderHeadDto.remark = $"{DateTime.Now.ToString()}生成";
            posOrderHeadDto.organizationId = "";
            posOrderHeadDto.branchId = store.branchId.ToString();
            posOrderHeadDto.branchName = store.branchName;
            //原价
            posOrderHeadDto.amountOrder = amountOrder;
            //应收
            posOrderHeadDto.amountDiscount = amountDiscount;
            //实收
            posOrderHeadDto.amountBalance = amountDiscount;
            //赠金
            posOrderHeadDto.amountFact = amountFact;//posOrderHeadDto.amountOrder - posOrderHeadDto.amountBalance;

            var nowTime = DateTime.Now;

            posOrderHeadDto.billDate = nowTime.ToString();
            posOrderHeadDto.billTime = nowTime.ToString();
            posOrderHeadDto.orderBillTypeId = orderBillTypeId.ToString();
            posOrderHeadDto.orderTypeId = "1";//OrderType.正常订单.GetHashCode().ToString();
            posOrderHeadDto.saleTypeId = "2"; //SaleType.线下.GetHashCode().ToString();
            posOrderHeadDto.saleSortId = "1";// SaleSort.门店.GetHashCode().ToString();
            posOrderHeadDto.pickType = "1";
            posOrderHeadDto.vipInfoId = member.id.ToString();
            posOrderHeadDto.vipNo = member.number.ToString();
            posOrderHeadDto.status = "5";//PosOrderHeadStatus.已生效.GetHashCode().ToString();
            posOrderHeadDto.auditer = user.userName;
            posOrderHeadDto.orderId = tableid;
            posOrderHeadDto.billNo = BillNo;
            posOrderHeadDto.warehouseId = store.id.ToString();
            posOrderHeadDto.dutycode = orderClass.classNumber;//InitDataModel.StaticData.userInfoData.data.UserDutyInfo.duty_code;
            posOrderHeadDto.sourceNo = sourceNo;

            //List<object> list = new List<object>()
            //{
            //    posOrderHeadDto
            //};

            //try
            //{
            //    BusTool.sqLiteDbDapper.Execute(SqlBuilder.DeleteSql(StaticStringTool.TABLE.POSORDERHEADDTO, new List<string>()
            //    {
            //    "@orderId"
            //    }), list);

            //    BusTool.sqLiteDbDapper.Execute(SqlBuilder.InsertSql(StaticStringTool.TABLE.POSORDERHEADDTO, new List<string>
            //    {
            //    "@remark",
            //    "@posOrderHeadId",
            //    "@tenantId",
            //    "@organizationId",
            //    "@billNo",
            //    "@branchId",
            //    "@branchNo",
            //    "@branchName",
            //    "@amountOrder",
            //    "@amountDiscount",
            //    "@amountBalance",
            //    "@amountFact",
            //    "@billDate",
            //    "@billTime",
            //    "@orderBillTypeId",
            //    "@orderTypeId",
            //    "@saleTypeId",
            //    "@saleSortId",
            //    "@vipInfoId",
            //    "@vipNo",
            //    "@outno",
            //    "@sourceNo",
            //    "@sHeadId",
            //    "@status",
            //    "@auditer",
            //    "@pickType",
            //    "@sBillno",
            //    "@sendType",
            //    "@sendCount",
            //    "@orderId",
            //    "@warehouseId",
            //    "@dutycode"
            //    }), list);
            //}
            //catch (Exception ex)
            //{
            //    LogManage.Info($"创建主订单信息出错:{ex.Message}");
            //}

            return posOrderHeadDto;
        }


        // <summary>
        /// 创建商品信息
        /// 虚拟商品使用
        /// </summary>
        /// <param name="priceBalance">虚拟商品结算价</param>
        /// <returns></returns>
        public List<PosOrderLineDto> CreateLineOrder4Virtual(object p, decimal amountDiscount, string tableId, decimal amountOrder = 0, decimal amountFact = 0)
        {
            List<PosOrderLineDto> posOrderLineDtos = new List<PosOrderLineDto>();
            List<object> list = new List<object>();

            PosOrderLineDto posOrderLineDto = new PosOrderLineDto();

            posOrderLineDto.Id = YitIdHelper.NextId();
            posOrderLineDto.spuId = "0";
            posOrderLineDto.qtyOrder = 0;
            posOrderLineDto.priceOrder = amountOrder;
            posOrderLineDto.priceDiscount = amountDiscount;
            posOrderLineDto.priceBalance = amountDiscount;
            posOrderLineDto.priceCost = amountDiscount;
            posOrderLineDto.amountOrder = amountOrder;
            posOrderLineDto.amountDiscount = amountDiscount;
            posOrderLineDto.amountBalance = amountDiscount;
            posOrderLineDto.amountCost = amountDiscount;
            posOrderLineDto.amountZ = amountFact;
            posOrderLineDto.status = "0";
            posOrderLineDto.spuCode = "0";
            posOrderLineDto.pdtSpuSpecId = "0";
            posOrderLineDto.spuName = "";
            posOrderLineDto.orderId = tableId;

            posOrderLineDtos.Add(posOrderLineDto);
            list.Add(posOrderLineDto);
            return posOrderLineDtos;
        }


        /// <summary>
        /// 创建现金支付信息
        /// </summary>
        /// <param name="cashDecimal"></param>
        /// <param name="discontZero">商家优惠，抹零</param>
        /// <returns></returns>
        public PosOrderBalDto CreateCashBal(string orderId, decimal cashDecimal, decimal amountFact = 0, decimal disCountPrice = 0)
        {
            PosOrderBalDto posOrderBalDto = new PosOrderBalDto();
            posOrderBalDto.Id = YitIdHelper.NextId();
            posOrderBalDto.baseBalanceTypeId = ((int)(Payment.cash)).ToString();//StaticStringTool.CASHPAYTYPEID;//现金支付
            posOrderBalDto.amountPayment = cashDecimal;
            posOrderBalDto.amountDiscount = cashDecimal;
            posOrderBalDto.amountFact = amountFact;
            posOrderBalDto.amountDisshop = disCountPrice;
            posOrderBalDto.accountCode = string.Empty;
            posOrderBalDto.paymentSn = string.Empty;// string.Empty.GetMchNo();
            posOrderBalDto.status = PayStatus.成功.GetHashCode().ToString();
            posOrderBalDto.orderId = orderId;
            return posOrderBalDto;
        }


        /// <summary>
        /// 得到订单下的商品信息
        /// </summary>
        /// <param name="tableid"></param>
        /// <returns></returns>
        public PosOrderHeadDto GetUpLoadOrderData(sysuser user, corecmsstore store, string classNo, long orderId)
        {
            var master = new corecmsfoodordermasterServices().GetById(orderId);

            List<corecmsfoodsaledetail> detail = new corecmsfoodorderdetailServices().QueryUpdataDetail(orderId, user);
            List<corecmsfoodorderclass> orderclass = new corecmsfoodorderclassServices().QueryUpdataOrderClass();
            List<corecmsfoodorderpayment> payments = new corecmsfoodorderpaymentServices().QueryOrderpayments(orderId, user);
            List<PosOrderLineDto> billLine = new List<PosOrderLineDto>();
            List<PosOrderBillPromoDto> billPromoList = new List<PosOrderBillPromoDto>();
            var posOrderHeadId = YitIdHelper.NextId();
            foreach (var item in detail)
            {
                PosOrderLineDto posOrderLineDto = new PosOrderLineDto();
                posOrderLineDto.orderId = orderId.ToString();
                posOrderLineDto.Id = item.id.Value;
                posOrderLineDto.warehouseId = user.storeId.ToString();
                posOrderLineDto.spuId = item.foodId.Value.ToString();
                posOrderLineDto.qtyOrder = item.quantity.Value;
                posOrderLineDto.qtyBacked = 0;
                posOrderLineDto.priceOrder = item.price.Value;
                posOrderLineDto.priceDiscount =  item.realPrice.Value;
                posOrderLineDto.priceBalance = item.realPrice.Value ;
                posOrderLineDto.amountOrder = item.amount.Value ;
                posOrderLineDto.amountDiscount = item.amount.Value;
                posOrderLineDto.amountBalance = item.allAmount.Value ;
                posOrderLineDto.amountFact = item.amount.Value - item.allAmount.Value; //item.reduceAmount.Value;
                posOrderLineDto.status = "1";
                posOrderLineDto.amountZ = item.amount.Value - item.allAmount.Value;
                //posOrderLineDto.spuCode=item.foodId.Value.ToString();   
                posOrderLineDto.spuName = item.foodName;
                posOrderLineDto.pdtSpuSpecId = item.foodSpecId.Value.ToString();
                posOrderLineDto.posOrderHeadId = posOrderHeadId.ToString();
                billLine.Add(posOrderLineDto);

                if (item.allAmount < item.amount && master.ordertype == (int)GlobalEnumVars.OrderBillType.Order)
                { //声明一条优惠记录
                    PosOrderBillPromoDto billPromo = new PosOrderBillPromoDto();
                    billPromo.spuId = item.foodId.ToString();
                    //billPromo.spuCode = item.helpCode;
                    billPromo.spuName = item.foodName;
                    billPromo.pdtSpuSpecId = item.foodSpecId.ToString();
                    billPromo.beforePrice = item.price + "";
                    billPromo.afterPrice = item.realPrice + "";
                    billPromo.amountBefore = item.amount.ToString();
                    billPromo.amountAfter = item.allAmount.ToString();
                    billPromo.qtyOrder = item.quantity + "";
                    billPromo.branchId = store.branchId.ToString();
                    billPromo.orderId = orderId.ToString();
                    billPromo.promoType = master.userId > 0 ? "1" : "3";
                    billPromo.billNo = master.orderNo;
                    billPromo.posOrderHeadId = posOrderHeadId.ToString();
                    billPromo.posOrderPromoId = posOrderLineDto.Id.ToString();                    
                    billPromo.billTime = master.orderDate.ToString("yyyy-MM-dd HH:mm:ss");
                    billPromoList.Add(billPromo);
                }
            }

            //创建支付方式
            decimal amountDisshop = master.sumReduceAmount;
            List<PosOrderBalDto> billBal = new List<PosOrderBalDto>();
            foreach (var payment in payments)
            {
                PosOrderBalDto line = new PosOrderBalDto();
                line.Id = payment.id;
                if (payment.tenantBalanceTypeId > 0)
                    line.baseBalanceTypeId = payment.tenantBalanceTypeId.ToString();
                else line.baseBalanceTypeId = payment.paymentId.ToString();
                line.amountDiscount = payment.payAmount;
                line.amountFact =  payment.payAmount;
                line.amountPayment = payment.payAmount;
                line.orderId = orderId.ToString();
                line.paymentSn = payment.payNo;
                line.orderSn = payment.payNo;
                line.posOrderHeadId = posOrderHeadId.ToString();
                line.status = PayStatus.成功.GetHashCode().ToString();
                line.amountDisshop = amountDisshop;
                amountDisshop = 0;//目前只分担到第一个支付上。
                billBal.Add(line);
            }

            PosOrderHeadDto posOrderHeadDto = new PosOrderHeadDto();
            posOrderHeadDto.posOrderHeadId = posOrderHeadId.ToString();
            posOrderHeadDto.amountBalance = master.sumAllAmount;
            posOrderHeadDto.amountDiscount = master.sumAmount;
            posOrderHeadDto.amountOrder = master.sumAmount;
            posOrderHeadDto.amountFact = master.sumReduceAmount;
            posOrderHeadDto.auditer = user.userName;
            posOrderHeadDto.billBal = billBal;
            posOrderHeadDto.billDate = master.orderDate.ToString();
            posOrderHeadDto.billLine = billLine;
            posOrderHeadDto.billNo =  master.orderNo.ToString() ;
            posOrderHeadDto.branchId = store.branchId.ToString();
            posOrderHeadDto.billTime = master.orderDate.ToString();
            posOrderHeadDto.orderBillTypeId = master.ordertype.ToString();
            posOrderHeadDto.orderId = orderId.ToString();
            posOrderHeadDto.orderTypeId = "1";
            posOrderHeadDto.pickType = "1";
            posOrderHeadDto.saleSortId = "1";
            posOrderHeadDto.status = "5";
            posOrderHeadDto.warehouseId = store.id.ToString();
            posOrderHeadDto.billPromo = billPromoList;
            posOrderHeadDto.sourceNo = CommFunc.ConvertToString(master.sourceNo);
            posOrderHeadDto.branchName = store.branchName.ToString();
            posOrderHeadDto.dutycode = classNo;
            posOrderHeadDto.tenantId = store.corpId.ToString();
            if (master.userId > 0)
            {
                posOrderHeadDto.vipInfoId = master.userId.ToString();
                posOrderHeadDto.pointsOrder = master.userPoint;
                posOrderHeadDto.pointsType = 1;
                var member = new corecmsuserServices().GetById(master.userId);
                if (member != null)
                   posOrderHeadDto.vipNo = member.mobile;
            }

            return posOrderHeadDto;
        }


        /// <summary>
        /// 得到订单下的商品信息
        /// </summary>
        /// <param name="tableid"></param>
        /// <returns></returns>
        public PosOrderHeadDto GetUserDepositData(corecmsuserbalance balance, sysuser user, corecmsstore store, string classNo, int orderBillTypeId = (int)OrderBillType.Deposit)
        {
            var nowTime = DateTime.Now;
            List<PosOrderLineDto> billLine = new List<PosOrderLineDto>();
            List<PosOrderBillPromoDto> billPromoList = new List<PosOrderBillPromoDto>();
            long orderId = CommFunc.GetCorpNextId(store.corpId, YitIdHelper.NextId());
            var posOrderHeadId = CommFunc.GetCorpNextId(store.corpId, YitIdHelper.NextId());

            PosOrderLineDto posOrderLineDto = new PosOrderLineDto();
            posOrderLineDto.orderId = orderId.ToString();
            posOrderLineDto.Id = YitIdHelper.NextId();
            posOrderLineDto.priceOrder = balance.money;
            posOrderLineDto.priceDiscount = balance.realAmount;
            posOrderLineDto.priceBalance = balance.realAmount;
            posOrderLineDto.amountOrder = balance.money;
            posOrderLineDto.amountDiscount = balance.realAmount;
            posOrderLineDto.amountBalance = balance.realAmount;
            posOrderLineDto.amountFact = balance.giftAmount;
            posOrderLineDto.amountZ = balance.giftAmount;
            posOrderLineDto.warehouseId = user.storeId.ToString();
            posOrderLineDto.spuId = "0";
            posOrderLineDto.qtyOrder = 0;
            posOrderLineDto.qtyBacked = 0;
            posOrderLineDto.amountCost = 0;            
            posOrderLineDto.status = "1";
            posOrderLineDto.spuName = "";
            posOrderLineDto.pdtSpuSpecId = "0";            
            posOrderLineDto.posOrderHeadId = posOrderHeadId.ToString();
            billLine.Add(posOrderLineDto);
            List<PosOrderBalDto> billBal = new List<PosOrderBalDto>();

            //创建支付方式
            var paymentInfo = new corecmspaymentsService().GetById(balance.paymentId);
            PosOrderBalDto balItem = new PosOrderBalDto();
            balItem.Id = YitIdHelper.NextId();
            if ((paymentInfo != null ) && (paymentInfo.tenantBalanceTypeId > 0))
                balItem.baseBalanceTypeId = paymentInfo.tenantBalanceTypeId.ToString();
            else 
                balItem.baseBalanceTypeId = balance.paymentId.ToString();
            balItem.amountDiscount = balance.realAmount; 
            balItem.amountFact = balance.giftAmount;//赠送金额
            balItem.amountPayment = balance.realAmount;
            balItem.orderId = orderId.ToString();
            balItem.paymentSn = "";
            balItem.orderSn = "";
            balItem.posOrderHeadId = posOrderHeadId.ToString();
            balItem.status = PayStatus.成功.GetHashCode().ToString();
            billBal.Add(balItem);

            PosOrderHeadDto posOrderHeadDto = new PosOrderHeadDto();
            posOrderHeadDto.posOrderHeadId = posOrderHeadId.ToString();
            posOrderHeadDto.amountBalance = posOrderLineDto.amountBalance;
            posOrderHeadDto.amountDiscount = posOrderLineDto.amountDiscount;
            posOrderHeadDto.amountOrder = posOrderLineDto.amountOrder;
            posOrderHeadDto.amountFact = posOrderLineDto.amountFact;
            posOrderHeadDto.auditer = user.userName;
            posOrderHeadDto.billBal = billBal;
            posOrderHeadDto.billDate = nowTime.ToString();
            posOrderHeadDto.billLine = billLine;
            posOrderHeadDto.billNo = orderBillTypeId.ToString() + YitIdHelper.NextId().ToString();
            posOrderHeadDto.branchId = store.branchId.ToString();
            posOrderHeadDto.billTime = nowTime.ToString();
            posOrderHeadDto.orderBillTypeId = orderBillTypeId.ToString();
            posOrderHeadDto.orderId = orderId.ToString();
            posOrderHeadDto.orderTypeId = "1";
            posOrderHeadDto.pickType = "1";
            posOrderHeadDto.saleSortId = "1";
            posOrderHeadDto.status = "5";
            posOrderHeadDto.warehouseId = store.id.ToString();
            posOrderHeadDto.billPromo = billPromoList;            
            posOrderHeadDto.branchName = store.branchName.ToString();
            posOrderHeadDto.dutycode = classNo;
            posOrderHeadDto.tenantId = store.corpId.ToString();
            posOrderHeadDto.vipInfoId = balance.userId.ToString();
            posOrderHeadDto.vipNo = balance.vipNo;            
            return posOrderHeadDto;
        }

        /// <summary>
        /// 创建会员充值单赠送的档位信息
        /// </summary>
        /// <returns></returns>
        public List<PosOrderBillVipPromoDto> CreateBillVipPromoDto(string Orderid, TopUpItemDataInfoMode DataValue)
        {
            try
            {
                if (DataValue == null) return null;

                List<PosOrderBillVipPromoDto> ListBillVipPromoDto = new List<PosOrderBillVipPromoDto>();
                PosOrderBillVipPromoDto BillVipPromoDto;
                if (!string.IsNullOrEmpty(DataValue.qty))
                {
                    BillVipPromoDto = new PosOrderBillVipPromoDto();
                    BillVipPromoDto.posOrderVipPromoId = YitIdHelper.NextId();
                    BillVipPromoDto.posOrderHeadId = Orderid;
                    BillVipPromoDto.posTxtOrderHeadId = Orderid;
                    BillVipPromoDto.promoType = 1;
                    BillVipPromoDto.promoId = long.Parse(DataValue.rechargeStandardId);
                    BillVipPromoDto.promoName = DataValue.rechargeStandardName;
                    BillVipPromoDto.value = DataValue.qty;
                    ListBillVipPromoDto.Add(BillVipPromoDto);
                }
                if (!string.IsNullOrEmpty(DataValue.couponBatchId))
                {
                    BillVipPromoDto = new PosOrderBillVipPromoDto();
                    BillVipPromoDto.posOrderVipPromoId = YitIdHelper.NextId();
                    BillVipPromoDto.posOrderHeadId = Orderid;
                    BillVipPromoDto.posTxtOrderHeadId = Orderid;
                    BillVipPromoDto.promoType = 2;
                    BillVipPromoDto.promoId = long.Parse(DataValue.rechargeStandardId);
                    BillVipPromoDto.promoName = DataValue.rechargeStandardName;
                    BillVipPromoDto.couponId = long.Parse(DataValue.couponBatchId);
                    ListBillVipPromoDto.Add(BillVipPromoDto);
                }                
                return ListBillVipPromoDto;
            }
            catch (Exception ex)
            {
                //Log.LogManage.Error("创建会员充值档位赠送信息错误" + ex);
                return null;
            }
        }

    }
}
